package org.sanelli.InterstellarGolf;

import org.sanelli.InterstellarGolf.GenericObject.*;
import org.sanelli.InterstellarGolf.SpecificObject.GamePlayer;
import org.sanelli.InterstellarGolf.SpecificObject.GameWorld;
import org.sanelli.InterstellarGolf.Thread.GameThread;
import org.sanelli.InterstellarGolf.Util.Scaling;

import android.content.Context;
import android.graphics.*;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class Game extends SurfaceView implements Callback {
	public GameWorld _world;
	private GameThread _thread;
	private boolean _running=false;
	
	public Game(Context context) {
		super(context);
		this._world = new GameWorld(context);
		this._world.LoadGame();
		getHolder().addCallback(this);
		this._thread = new GameThread(getHolder(), this);
		setFocusable(true);
	}
	
	public void onDraw(Canvas canvas) {
		this._world.initBoundingBox();
		Scaling.calculateScaling(_world);
		canvas.drawColor(Color.BLACK);
		this._world.onDraw(canvas);
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		synchronized (holder) {
			Canvas canvas = holder.lockCanvas();
			this.onDraw(canvas);
			holder.unlockCanvasAndPost(canvas);	
		}
	}
	
	@Override
    public boolean onTouchEvent(MotionEvent e) {
		if (!this._running) {
			switch (e.getAction()) {
			case MotionEvent.ACTION_MOVE:
				/*Freccia?*/
				GamePlayer player = this._world.getPlayer();

				player.setSpeed(new Vector2D(1082, 0));
				break;
			case MotionEvent.ACTION_UP:
				this._running=true;
				_thread.setRunning(true);
				_thread.start();
				try {
					Thread.sleep(600000000);
				} catch (InterruptedException e1) {
					_thread.setRunning(false);
					_thread.interrupt();
					this._running=false;
				}
				finally {
					_thread.setRunning(false);
					this._running=false;
				}
				break;				
			default:
				break;
			}
		}
		return true;
	}

	public void updatePhysic(long timesincelastframe) {
		this._world.updatePhysic(timesincelastframe);
	}
	
	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {	
		
	}

}
